﻿using Microsoft.EntityFrameworkCore;
using Model.ApiResult.MessageRsult;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;

namespace BLL.Manage
{
    public class MessageManage
    {
        /// <summary>
        /// 获取新消息
        /// </summary>
        public Model.Result<List<NewsChatMessage>> GetNewMessage(string messageId, string roomId)
        {
            UserManage user = new UserManage();
            using (Model.Entity.DBContext context = new Model.Entity.DBContext())
            {
                var friendId = "";
                var findRoom = context.Friends.FirstOrDefault(p => p.MemberId == user.UserTokenModel.MemberId && p.FriendRelationId == roomId);
                if (findRoom == null)
                {
                    return RestfulAPIModel.ErrorReult<List<NewsChatMessage>>("还不是好友");
                }
                else
                {
                    friendId = findRoom.FriendMemberId;
                }
                FriendsManage friendsManage = new FriendsManage();
                bool isFriend = friendsManage.IsFriends(friendId);
                if (isFriend)
                {
                    Model.Entity.ChatMessage findMessage = null; // context.ChatMessage.FirstOrDefault(p => p.MessageId == messageId);
                    if (!String.IsNullOrEmpty(messageId))
                    {
                        findMessage = context.ChatMessage.FirstOrDefault(p => p.MessageId == messageId);
                        if (findMessage == null)
                        {
                            return RestfulAPIModel.ErrorReult<List<NewsChatMessage>>("未找到消息记录");
                        }
                    }
                    var sqlParams = new MySql.Data.MySqlClient.MySqlParameter[]
                        {
                                new MySql.Data.MySqlClient.MySqlParameter("@sender_id",user.UserTokenModel.MemberId),
                                new MySql.Data.MySqlClient.MySqlParameter("@room_id",roomId)
                        };
                    string sql = @"
                                    SELECT
	                                    C.*,
                                        U1.nick_name AS sender_nick_name,
                                        F1.friend_remark AS sender_remark_name,
                                        U1.avatar as sender_avatar,
                                        U2.nick_name AS receiver_nick_name,
                                        F2.friend_remark AS receiver_remark_name,
                                        U2.avatar as receiver_avatar
                                    FROM
	                                    chat_message C
                                    LEFT JOIN `user` U1 ON U1.member_id = C.sender_id
                                    LEFT JOIN `user` U2 ON U2.member_id = C.receiver_id
                                    LEFT JOIN `friends` F1 ON F1.friend_relation_id = C.chat_room_id AND C.sender_id = F1.member_id
                                    LEFT JOIN `friends` F2 ON F2.friend_relation_id = C.chat_room_id AND C.receiver_id = F2.member_id
                                    WHERE C.chat_room_id = @room_id
                                    AND C.receiver_status = 1
                                    AND C.create_time > @create_time
                                    ORDER BY C.create_time";

                    //  "SELECT
                    //      *
                    //  FROM
                    //      chat_message
                    //  WHERE chat_message.create_time > @create_time
                    //  AND (
                    //      (
                    //          chat_message.sender_id = @sender_id
                    //          AND chat_message.receiver_id = @receiver_id
                    //      )
                    //      OR (
                    //          chat_message.receiver_id = @sender_id
                    //          AND chat_message.receiver_status = 1
                    //          AND chat_message.sender_id =@receiver_id
                    //      )
                    //  ) ORDER BY chat_message.create_time DESC"
                    if (findMessage != null)
                    {
                        sql += ";";
                        sqlParams = sqlParams.Append(new MySql.Data.MySqlClient.MySqlParameter("@create_time", findMessage.CreateTime.ToString("yyyy-MM-dd HH:mm:ss"))).ToArray();
                    }
                    else
                    {
                        sql += ";";
                        sqlParams = sqlParams.Append(new MySql.Data.MySqlClient.MySqlParameter("@create_time", "2011-11-11 11:11:11")).ToArray();
                    }
                    var table = MySqlDb.GetDataTable(sql, sqlParams);
                    MySqlDb.ExecuteNonQuery("UPDATE chat_message SET is_read = 1  where chat_room_id=@room_id and receiver_id=@sender_id", sqlParams);
                    List<NewsChatMessage> chatMessagesList = MySqlDb.ErgodicDataTable(table, (DataRow dr) =>
                    {
                        return new NewsChatMessage()
                        {
                            MessageId = MySqlDb.ChangeTableData<string>(dr["message_id"]),
                            SenderId = MySqlDb.ChangeTableData<string>(dr["sender_id"]),
                            ReceiverId = MySqlDb.ChangeTableData<string>(dr["receiver_id"]),
                            Content = MySqlDb.ChangeTableData<string>(dr["content"]),
                            ContentType = MySqlDb.ChangeTableData<int>(dr["content_type"]),
                            MessageType = MySqlDb.ChangeTableData<int>(dr["message_type"]),
                            IsRead = MySqlDb.ChangeTableData<int>(dr["is_read"]),
                            ReadTime = MySqlDb.ChangeTableData<DateTime>(dr["read_time"]),
                            CreateTime = MySqlDb.ChangeTableData<DateTime>(dr["create_time"]),
                            IsReceiver = MySqlDb.ChangeTableData<int>(dr["is_receiver"]),
                            ReceiverTime = MySqlDb.ChangeTableData<DateTime>(dr["receiver_time"]),
                            ReceiverStatus = MySqlDb.ChangeTableData<int>(dr["receiver_status"]),
                            ChatRoomId = MySqlDb.ChangeTableData<string>(dr["chat_room_id"]),
                            SenderNickName = MySqlDb.ChangeTableData<string>(dr["sender_nick_name"]),
                            SenderRemarkName = MySqlDb.ChangeTableData<string>(dr["sender_remark_name"]),
                            SenderAvatar = MySqlDb.ChangeTableData<string>(dr["sender_avatar"]),
                            ReceiverNickName = MySqlDb.ChangeTableData<string>(dr["receiver_nick_name"]),
                            ReceiverRemarkName = MySqlDb.ChangeTableData<string>(dr["receiver_remark_name"]),
                            ReceiverAvatar = MySqlDb.ChangeTableData<string>(dr["receiver_avatar"]),
                        };
                    });
                    // List<Model.Entity.ChatMessage> chatMessagesList = context.ChatMessage
                    //     .FromSql(sql, sqlParams)
                    //     .ToList();
                    return RestfulAPIModel.SuccessReult<List<NewsChatMessage>>(chatMessagesList);

                }
                else
                {
                    return RestfulAPIModel.ErrorReult<List<NewsChatMessage>>("不是好友");
                }
            };
        }
        public Model.Result<List<Model.ApiResult.MessageRsult.NewChatMessageList>> GetNewChatMessageList(string roomId = null)
        {
            UserManage user = new UserManage();
            var sqlParams = new MySql.Data.MySqlClient.MySqlParameter[]{
                   new MySql.Data.MySqlClient.MySqlParameter("@user_member_id",user.UserTokenModel.MemberId)
            };
            var table = MySqlDb.GetDataTable(
                @"
                SELECT
	                C.*, 
	                COUNT(C.message_id) AS count,
	                U1.nick_name AS sender_nick_name,
	                F1.friend_remark AS sender_remark_name,
                    U1.avatar as sender_avatar,
	                U2.nick_name AS receiver_nick_name,
	                F2.friend_remark AS receiver_remark_name,
                    U2.avatar as receiver_avatar
                FROM
	                (
		                SELECT
			                *
		                FROM
			                chat_message,
			                (SELECT 0) a
		                ORDER BY
			                create_time DESC
		                LIMIT 1000
	                ) C
                LEFT JOIN `user` U1 ON U1.member_id = C.sender_id
                LEFT JOIN `user` U2 ON U2.member_id = C.receiver_id
                LEFT JOIN `friends` F1 ON F1.friend_relation_id = C.chat_room_id
                AND C.sender_id = F1.member_id
                LEFT JOIN `friends` F2 ON F2.friend_relation_id = C.chat_room_id
                AND C.receiver_id = F2.member_id
                WHERE
	                C.chat_room_id IS NOT NULL "
                + (string.IsNullOrEmpty(roomId) ? "" : " AND C.chat_room_id='" + roomId + "' ") +
                @"AND C.receiver_status = 1
                AND C.is_read = 0
                AND (
	                C.sender_id = @user_member_id
	                OR C.receiver_id = @user_member_id
                )
                GROUP BY
	                chat_room_id
                ORDER BY create_time;", sqlParams);

            var table1 = MySqlDb.GetDataTable(
            @"
                SELECT
	                C.chat_room_id,
	                COUNT(C.chat_room_id) AS count
                FROM
	                chat_message C
                WHERE
	                C.chat_room_id IS NOT NULL
                AND C.receiver_status = 1
                AND C.is_read = 0
                AND C.receiver_id = @user_member_id
                GROUP BY C.chat_room_id
                ORDER BY C.create_time;", sqlParams);

            var dict = new Dictionary<string, int>();
            MySqlDb.ErgodicDataTable(table1, (DataRow dr) =>
            {
                dict.Add(MySqlDb.ChangeTableData<string>(dr["chat_room_id"]), MySqlDb.ChangeTableData<int>(dr["count"]));
                return MySqlDb.ChangeTableData<string>(dr["chat_room_id"]);
            });
            return RestfulAPIModel.SuccessReult<List<Model.ApiResult.MessageRsult.NewChatMessageList>>(MySqlDb.ErgodicDataTable(table, (DataRow dr) =>
            {
                var model = new Model.ApiResult.MessageRsult.NewChatMessageList()
                {
                    SenderId = MySqlDb.ChangeTableData<string>(dr["sender_id"]),
                    SenderNickName = MySqlDb.ChangeTableData<string>(dr["sender_nick_name"]),
                    SenderRemarkName = MySqlDb.ChangeTableData<string>(dr["sender_remark_name"]),
                    SenderAvatar = MySqlDb.ChangeTableData<string>(dr["sender_avatar"]),
                    ReceiverId = MySqlDb.ChangeTableData<string>(dr["receiver_id"]),
                    ReceiverNickName = MySqlDb.ChangeTableData<string>(dr["receiver_nick_name"]),
                    ReceiverRemarkName = MySqlDb.ChangeTableData<string>(dr["receiver_remark_name"]),
                    ReceiverAvatar = MySqlDb.ChangeTableData<string>(dr["receiver_avatar"]),
                    Content = MySqlDb.ChangeTableData<string>(dr["content"]),
                    MessageCount = MySqlDb.ChangeTableData<int>(dr["count"]),
                    ChatRoomId = MySqlDb.ChangeTableData<string>(dr["chat_room_id"]),
                    CreateTime = MySqlDb.ChangeTableData<DateTime>(dr["create_time"])
                };
                var find = dict.TryGetValue(model.ChatRoomId, out int count);
                if (find)
                {
                    model.MessageCount = count;
                }
                else
                {
                    model.MessageCount = 0;
                }
                return model;
            }));
        }

    }



}
